package com.example.rbac.service;

import com.example.rbac.beans.CacheKeyConstants;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author XieLongzhen
 * @date 2019/2/21 17:31
 */
@Service
@Slf4j
public class SysCacheService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
        saveCache(toSavedValue, timeoutSeconds, prefix);
    }

    public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
        if (toSavedValue == null) {
            return;
        }
        String cacheKey = generateCacheKey(prefix, keys);
        stringRedisTemplate.opsForValue().set(cacheKey, toSavedValue, timeoutSeconds, TimeUnit.SECONDS);
    }

    public String getFromCache(CacheKeyConstants prefix, String... keys) {
        String cacheKey = generateCacheKey(prefix, keys);
        String value = stringRedisTemplate.opsForValue().get(cacheKey);
        return value;
    }

    private String generateCacheKey(CacheKeyConstants prefix, String... keys) {
        String key = prefix.name();
        if (keys != null && keys.length > 0) {
            key += "_" + Joiner.on("_").join(keys);
        }
        return key;
    }
}
